﻿using Mbs.Configuration;
using Mbs.Elements;
using Mbs.MessageService;
using Mbs.Modularity.AddIns;
using Mbs.Reflection;
using Mbs.ComponentModel.Container;

namespace Mbs.Windows.Elements.Builders
{
    [Component(Id = "Smartpart", Service = typeof(IElementBuilder))]
    public class SmartPartBuilder:ElementBuilder
    {
        public override object Create(object caller, IAddInItem element)
        {
            var strType = element.Properties.Get<string>("SmartPartType");
            if (string.IsNullOrEmpty(strType))
            {
                MsgBox.ShowWarning("SmartPartType == null :" + element.ToString());
                return null;
            }

            var classLoader = ServiceLocator.Current.Get<IClassLoader>();

            var type = classLoader.LoadType(strType);
            if (type == null)
            {
                MsgBox.ShowWarning("SmartPartType is invalid :" + element.ToString());
                return null;
            }

            var o = classLoader.NewInstance(type);
            
            var smartPart = o as ISmartPartView;
            if (smartPart != null)
            {
                smartPart.Load(element);

                smartPart.WorkspaceName = element.Properties.Get<string>("Workspace");
                var strSmartPartInfoType = element.Properties.Get<string>("SmartPartInfoType");

                if (string.IsNullOrEmpty(strSmartPartInfoType))
                    return o;

                var smartPartInfoType = classLoader.LoadType(strSmartPartInfoType);
                if (smartPartInfoType != null
                    && typeof(ISmartPartInfo).IsAssignableFrom(smartPartInfoType)
                    && element.Extensions.Length > 0)
                {
                    smartPart.SmartPartInfo = classLoader.NewInstance<ISmartPartInfo>(smartPartInfoType);
                    PopulateSmartPart(element.Extensions[0], smartPart.SmartPartInfo);
                }
            }
            return o;
        }

        private static void PopulateSmartPart(INode node, ISmartPartInfo info)
        {
            if (info == null) return;
            var loader = info as INodeLoader;
            loader.Load(node);
        }
    }
}
